import { Buffer } from 'node:buffer';

import { defineEventHandler, getQuery } from 'h3';

// 导出Excel文件需要的依赖（在Mock环境中模拟）
interface ExportResponse {
  filename: string;
  content: string; // Base64编码的Excel文件内容
}

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const { month } = query;

    // 验证月份参数
    if (!month || typeof month !== 'string') {
      return {
        success: false,
        data: null,
        message: '缺少统计月份参数',
      };
    }

    // 模拟生成Excel文件内容
    // 在实际项目中，这里会使用xlsx等库生成真正的Excel文件
    // 这里我们返回一个模拟的CSV格式内容作为Base64编码

    const csvContent = `司机ID,司机姓名,联系电话,当月省内公里数,当月省外公里数,省内补贴标准(元/公里),省外补贴标准(元/公里),补贴总费用(元),数据更新时间
1001,张三,13800138001,2800,1200,0.8,1.2,3680.00,2024-01-15 14:30:25
1002,李四,13800138002,3200,800,0.8,1.2,3520.00,2024-01-15 16:45:12
1003,王五,13800138003,2500,1500,0.8,1.2,3800.00,2024-01-15 10:15:33
1004,赵六,13800138004,3500,1000,0.8,1.2,4000.00,2024-01-15 18:20:45
1005,钱七,13800138005,2900,1100,0.8,1.2,3640.00,2024-01-15 12:30:18
1006,孙八,13800138006,3100,900,0.8,1.2,3560.00,2024-01-15 15:40:55
1007,周九,13800138007,2700,1300,0.8,1.2,3720.00,2024-01-15 09:25:41
1008,吴十,13800138008,3300,700,0.8,1.2,3480.00,2024-01-15 17:10:28
1009,郑十一,13800138009,2600,1400,0.8,1.2,3760.00,2024-01-15 13:55:39
1010,陈十二,13800138010,3000,1000,0.8,1.2,3600.00,2024-01-15 11:30:47`;

    // 将CSV内容转换为Base64
    const base64Content = Buffer.from(csvContent, 'utf8').toString('base64');

    // 生成文件名
    const filename = `司机补贴统计报表_${month.replace('-', '')}.xlsx`;

    const response: ExportResponse = {
      filename,
      content: base64Content,
    };

    return {
      success: true,
      data: response,
      message: '导出成功',
    };
  } catch (error) {
    console.error('导出司机补贴统计数据失败:', error);
    return {
      success: false,
      data: null,
      message: '导出失败',
    };
  }
});
